package com.lanshiqin.webdemo.service.bug;

import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Service
public class OfficeConvertService {

    /**
     * 临时目录
     */
    private static final String OFFICE_CONVERT_TEMP_DIR = "./data/bug/";

    private int DPI = 96;

    /**
     * 将pdf转换为图片列表
     * @param pdfFileUrl pdf文件url
     * @return 图片ur列表
     */
    public List<String> pdfConvertToImg(String pdfFileUrl, String fileName) throws IOException {

        try(InputStream in = new URL(pdfFileUrl).openStream();
            // 加载到外部临时文件
            PDDocument document = PDDocument.load(in)){
            // 不使用资源缓存
            document.setResourceCache(null);
            PDFRenderer renderer = new PDFRenderer(document);
            List<String> imgUrlList = Lists.newArrayList();
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                // 按页进行转换
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                File tempFile = new File(OFFICE_CONVERT_TEMP_DIR + fileName + "_" + i);
                try {
                    ImageIO.write(bufferedImage, "png", tempFile);
                    imgUrlList.add("todo "+i);
                    System.out.println("current is : "+ i);
                } finally {
                    // 删除图片，关闭BufferedImage资源
                    FileUtils.deleteQuietly(tempFile);
                    bufferedImage.getGraphics().dispose();
                }
            }
            return imgUrlList;
        }

    }
}
